﻿#region ... Copyright Notice ...
/*
   Copyright 2008 Tyler Jensen

	Author: Tyler Jensen    http://www.tsjensen.com/blog

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
#endregion

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace Atrax.Web.Test
{
	public static class QueryFactory
	{
		const string licenseKey = "MT83P-XGCY3-T3BBE-PRT5D-4983P";  //userId=2001
		const string privateKey = "michaelrowyourboat";
		static string callbackUrl = ConfigurationManager.AppSettings["callbackUrl"];
		static string notificationEmail = ConfigurationManager.AppSettings["notificationEmail"];

		public static string Create(string clientQueryId, string queryType, int priority, string queryRequest)
		{
			string timeStamp = CreateTimeStamp();
			string authorizationCode = CreateAuthorizationCode(timeStamp);
			string data = "key=" + HttpUtility.UrlEncode(licenseKey)
				+ "&time=" + HttpUtility.UrlEncode(timeStamp)
				+ "&code=" + HttpUtility.UrlEncode(authorizationCode)
				+ "&id=" + HttpUtility.UrlEncode(clientQueryId)
				+ "&type=" + HttpUtility.UrlEncode(queryType)
				+ "&url=" + HttpUtility.UrlEncode(callbackUrl)
				+ "&email=" + HttpUtility.UrlEncode(notificationEmail)
				+ "&priority=" + priority.ToString()
				+ "&query=" + HttpUtility.UrlEncode(queryRequest);
			return data;
		}

		public static string CreateAuthorizationCode(string timeStamp)
		{
			string input = licenseKey + "|" + timeStamp + "|" + privateKey + "|AtraxSaltAndPepper";	
			MD5 md5 = MD5CryptoServiceProvider.Create();
			byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
			md5.Clear();
			return Convert.ToBase64String(hash);  //authcode should be in base64 string
		}

		public static string CreateTimeStamp()
		{
 			return DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
		}
	}
}
